package servlet.register;

import pojo.User;
import redis.clients.jedis.Jedis;
import service.UserService;
import service.impl.UserServiceImpl;
import util.JedisUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/RegisterByPhoneServlet",name = "RegisterByPhoneServlet")
public class RegisterByPhoneServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String loginName = request.getParameter("login_name");
        String password = request.getParameter("password");

        String phone = request.getParameter("phone");
        String code = request.getParameter("code");


        String key = "register::"+phone;
        Jedis jedis = JedisUtil.getJedis();

        if(!jedis.exists(key)){
            response.getWriter().print("验证码错误");
            return;
        }

        String value = jedis.get(key);

        if (!value.equals(code)) {
            response.getWriter().print("验证码错误");
            return;
        }

        jedis.del(key);

        JedisUtil.closeJedis(jedis);

        User user = new User();
        user.setLoginName(loginName);
        user.setPassword(password);
        user.setStatus(1); //激活状态
        user.setUsername(loginName);
        user.setPhone(phone);
        if(userService.add(user)){
            response.getWriter().print("注册成功！用户名："+loginName+", 密码："+password+",手机："+phone);
        } else {
            response.getWriter().print("注册失败！");
        }

    }
}
